﻿using Awaken.Utils.CacheProvider;
using Awaken.Utils.WidgetCode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace Awaken.MessageProvider
{
    /// <summary>
    /// 短信验证码发送服务
    /// </summary>
    public class ParityCodeService
    {
        private static volatile ParityCodeService _instance;

        private static readonly object _locker = new object();

        private ParityCodeService()
        {

        }

        public static ParityCodeService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_locker)
                    {
                        if (_instance == null)
                        {
                            _instance = new ParityCodeService();
                        }
                    }
                }

                return _instance;
            }
        }

        /// <summary>
        /// 发送前 需校验 发送 TOKEN ，页面防重复TOKEN
        /// </summary>
        public string GenerateCodeSerial()
        {
            var serialKey = SerialGenerator.Generate(SerialType.Normal, 12);

            //var code = SerialGenerator.GenerateNumber(6);

            // 短信验证码发送有效时间 30分钟内能重复发送
            var policy = new CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddMinutes(30)
            };

            ParityCodeCache.Instance.Update(serialKey, "validKey", policy);

            return serialKey;
        }

        /// <summary>
        /// 发送次数有效性
        /// </summary>
        /// <param name="phoneNo"></param>
        /// <returns></returns>
        private bool ValidTimes(string phoneNo)
        {
            //同一IP地址 一小时内只能使用 15次
            var clientIp = ServerInfo.GetClientIP();

            if (ParityCodeCache.Instance.Count(clientIp) >= 50)
            {
                return false;
            }

            //同一手机号码 一小时内只能使用 3次
            if (ParityCodeCache.Instance.Count(phoneNo) >= 10)
            {
                return false;
            }

            return true;
        }


        /// <summary>
        /// 短信验证码模板
        /// </summary>
        public class CodeMessageTemplate
        {
            public const string Default = "验证码{0}，您正在操作魔方官网绑定，请在3分钟内完成填写。了解详情http://www.52mf.com.cn";


        }
    }
}
